"""
Elasticsearch API接口
提供与前端交互的ES相关API
"""
from django.http import JsonResponse
from elasticsearch import Elasticsearch
from django.views.decorators.http import require_http_methods
import logging


from .es_sync import ElasticsearchSyncManager
from ..models import MedicalArticle

from ..mysql_es_sync import start_sync_process, stop_sync_process

logger = logging.getLogger('elasticsearch')

@require_http_methods(["GET"])
def import_articles_to_es(request):
    """
    将所有文章导入到ES
    接口: GET /background/es/import-articles/
    """
    try:
        articles = MedicalArticle.objects.all()
        success_count = 0
        fail_count = 0
        
        for article in articles:
            result = ElasticsearchSyncManager.sync_article_to_es(article)
            if result:
                success_count += 1
            else:
                fail_count += 1
        
        return JsonResponse({
            "status": "success", 
            "message": f"文章数据导入完成: 成功 {success_count} 条, 失败 {fail_count} 条"
        })
        
    except Exception as e:
        logger.error(f"导入文章到ES失败: {str(e)}")
        return JsonResponse({
            "status": "error", 
            "message": f"导入文章到ES失败: {str(e)}"
        }, status=500)

@require_http_methods(["GET"])
def search_articles(request):
    """
    搜索文章
    接口: GET /background/es/search/?query=关键词
    """
    query = request.GET.get('query', '')
    if not query:
        return JsonResponse({
            "status": "error", 
            "message": "搜索关键词不能为空"
        }, status=400)
    
    try:
        es = ElasticsearchSyncManager.get_es_client()
        
        # 构建搜索查询
        body = {
            "query": {
                "bool": {
                    "should": [
                        {"match": {"title": {"query": query, "boost": 3}}},
                        {"match": {"content": {"query": query, "boost": 1}}},
                        {"match": {"tags": {"query": query, "boost": 2}}}
                    ]
                }
            },
            "highlight": {
                "fields": {
                    "title": {"pre_tags": ["<em>"], "post_tags": ["</em>"]},
                    "content": {"pre_tags": ["<em>"], "post_tags": ["</em>"], "fragment_size": 150, "number_of_fragments": 1}
                }
            },
            "_source": ["id", "title", "author", "department_name", "tags", "view_count", "like_count", "created_at"],
            "size": 20
        }
        
        # 执行搜索
        response = es.search(index=ElasticsearchSyncManager.INDEX_NAME, body=body)
        
        # 处理结果
        results = []
        for hit in response['hits']['hits']:
            source = hit['_source']
            
            # 处理高亮
            highlight = hit.get('highlight', {})
            if 'title' in highlight:
                source['title_highlight'] = highlight['title'][0]
            if 'content' in highlight:
                source['content_preview'] = highlight['content'][0]
            else:
                # 如果没有高亮，截取内容前150个字符作为预览
                source['content_preview'] = hit.get('content', '')[:150] + '...'
                
            results.append(source)
        
        return JsonResponse({
            "status": "success",
            "count": len(results),
            "results": results
        })
        
    except Exception as e:
        logger.error(f"搜索文章时出错: {str(e)}")
        return JsonResponse({
            "status": "error", 
            "message": f"搜索文章失败: {str(e)}"
        }, status=500)

@require_http_methods(["GET", "POST"])
def sync_control(request):
    """
    控制MySQL到ES的实时同步
    接口: 
      GET /background/es/sync/?action=status 获取同步状态
      POST /background/es/sync/?action=start 启动同步
      POST /background/es/sync/?action=stop 停止同步
    """
    action = request.GET.get('action', 'status')
    
    if action == 'status':
        from ..mysql_es_sync import sync_running
        return JsonResponse({
            "status": "success",
            "sync_status": "running" if sync_running else "stopped"
        })
    
    elif action == 'start':
        success, message = start_sync_process()
        return JsonResponse({
            "status": "success" if success else "error",
            "message": message
        })
    
    elif action == 'stop':
        success, message = stop_sync_process()
        return JsonResponse({
            "status": "success" if success else "error",
            "message": message
        })
    
    else:
        return JsonResponse({
            "status": "error",
            "message": f"未知的操作: {action}"
        }, status=400) 